package com.lfd.rabbitmq.service;

import com.lfd.rabbitmq.config.RabbitConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

/**
 * @项目名： spring-emq
 * @包名： com.lfd.rabbitmq.producer
 * @文件名: MessageProducer
 * @创建者: liufudong@szyh-smart.com
 * @创建时间: 2024/9/30 15:37
 * @描述：
 */
@Slf4j
@Service

public class MessageProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    public void sendMessageWithReturn(String message) {
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                assert correlationData != null;
                log.info("Message sent successfully: {}", correlationData.getId());
            } else {
                log.info("Message failed: {}", cause);
            }
        });
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                log.info("Message returned: {}", new String(returnedMessage.getMessage().getBody()));

            }
        });
        // 发送一条消息
        rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME, RabbitConfig.ROUTING_KEY, message);
    }

    public void sendMessage(String message) {
        // 发送消息并等待确认
        rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME, RabbitConfig.ROUTING_KEY, message,
                messagePostProcessor -> {
                    messagePostProcessor.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    return messagePostProcessor;
                });
    }
}
